/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.parkingwang.vehicle_keyboard_ohos.slice;

import com.parkingwang.keyboard.KeyboardInputController;
import com.parkingwang.keyboard.OnInputChangedListener;
import com.parkingwang.keyboard.PopupKeyboard;
import com.parkingwang.keyboard.view.InputView;
import com.parkingwang.vehicle_keyboard_ohos.ResourceTable;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Checkbox;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.StackLayout;
import ohos.agp.components.Text;
import ohos.agp.components.TextField;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.ToastDialog;

import java.util.ArrayList;
import java.util.List;

/**
 * Demo启动页面
 *
 * @since 2021-03-01
 */
public class MainAbilitySlice extends AbilitySlice {
    private static final int NEW_ENERGY_INDEX = 11;

    private StackLayout outRoot;
    private PopupKeyboard popupKeyboard;
    private Button changeNewEnergy;
    private TextField textField;
    private Button testData;
    private Button txtCommit;
    private Button showOrHideKeyboardButton;
    private Button showDialogButton;
    private Button clearButton;
    private Checkbox changeRule;

    private InputView inputView;

    private final List<String> mTestNumber = new ArrayList<>();
    private long mTestIndex = 0L;
    private boolean isHideOkKey;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        initView();
        initData();
        setListener();
    }

    private void initView() {
        inputView = (InputView) findComponentById(ResourceTable.Id_input);
        outRoot = (StackLayout) findComponentById(ResourceTable.Id_out_root);
        popupKeyboard = new PopupKeyboard(this);
        popupKeyboard.attach(inputView, getAbility(), outRoot);
        changeRule = (Checkbox) findComponentById(ResourceTable.Id_change_rule);
        changeRule.setChecked(true);
        testData = (Button) findComponentById(ResourceTable.Id_test_data);
        txtCommit = (Button) findComponentById(ResourceTable.Id_commit_text_city);
        showOrHideKeyboardButton = (Button) findComponentById(ResourceTable.Id_show_hide_keyboard);
        showDialogButton = (Button) findComponentById(ResourceTable.Id_show_dialog);
        textField = (TextField) findComponentById(ResourceTable.Id_input_edit);
        changeNewEnergy = (Button) findComponentById(ResourceTable.Id_change_newstargy);
        clearButton = (Button) findComponentById(ResourceTable.Id_clear_data);
    }

    private void initData() {
        mTestNumber.add("粤A12345");
        mTestNumber.add("粤BD12345");
        mTestNumber.add("粤Z1234港");
        mTestNumber.add("WJ粤12345");
        mTestNumber.add("WJ粤1234X");
        mTestNumber.add("NA00001");
        mTestNumber.add("123456使");
        mTestNumber.add("使123456");
        mTestNumber.add("粤A1234领");
        mTestNumber.add("粤12345领");
        mTestNumber.add("民航12345");
        mTestNumber.add("粤C0");
        mTestNumber.add("粤");
        mTestNumber.add("WJ粤12");
        mTestNumber.add("湘E123456");
    }

    private void setListener() {
        popupKeyboard.getController().addOnInputChangedListener(new OnInputChangedListener() {
            @Override
            public void onChanged(String number, boolean isCompleted) {
                if (isCompleted) {
                    popupKeyboard.dismiss(getAbility(), outRoot);
                }
            }

            @Override
            public void onCompleted(String number, boolean isAutoCompleted) {
                popupKeyboard.dismiss(getAbility(), outRoot);
            }
        });
        popupKeyboard.getController()
                .setDebugEnabled(true)
                .setSwitchVerify(changeRule.isChecked())
                .bindLockTypeProxy(new KeyboardInputController.ButtonProxyImpl(changeNewEnergy) {
                    @Override
                    public void onNumberTypeChanged(boolean isNewEnergyType) {
                        super.onNumberTypeChanged(isNewEnergyType);
                        if (isNewEnergyType) {
                            changeNewEnergy.setTextColor(new Color(Color.getIntColor("#ff99cc00")));
                        } else {
                            changeNewEnergy.setTextColor(new Color(Color.getIntColor("#ff000000")));
                        }
                    }
                });
        changeRule.setCheckedStateChangedListener((absButton, b) -> popupKeyboard.getController().setSwitchVerify(b));
        clearButton.setClickedListener(component -> popupKeyboard.getController().updateNumber(""));
        testData.setClickedListener(component -> {
            final int idx = (int) (mTestIndex % mTestNumber.size());
            mTestIndex++;

            // 上面测试例子中，第12个，指定为新能源车牌，部分车牌
            if (idx == NEW_ENERGY_INDEX) {
                popupKeyboard.getController().updateNumberLockType(mTestNumber.get(idx), true);
            } else {
                popupKeyboard.getController().updateNumber(mTestNumber.get(idx));
            }
        });
        txtCommit.setClickedListener(component -> {
            String text = textField.getText();
            popupKeyboard.getKeyboardEngine().setLocalProvinceName(text);

            showToast("演示“周边省份”重新排序，将在下一个操作中生效：" + text);
        });
        showOrHideKeyboardButton.setClickedListener(component -> {
            if (popupKeyboard.isShown()) {
                popupKeyboard.dismiss(MainAbilitySlice.this.getAbility(), outRoot);
            } else {
                popupKeyboard.show(getAbility(), outRoot);
            }
        });
        showDialogButton.setClickedListener(component -> new VehicleDialog(MainAbilitySlice.this).show());
        findComponentById(ResourceTable.Id_show_hide_confirm).setClickedListener(component -> {
            isHideOkKey = !isHideOkKey;
            popupKeyboard.getKeyboardEngine().setHideOKKey(isHideOkKey);

            showToast("演示“确定”键盘状态，将在下一个操作中生效: " + (isHideOkKey ? "隐藏" : "显示"));
        });
        inputView.performFirstFieldView();
    }

    /**
     * 显示toast
     *
     * @param msg 消息内容
     */
    private void showToast(String msg) {
        DirectionalLayout layout = (DirectionalLayout) LayoutScatter.getInstance(getContext())
                .parse(ResourceTable.Layout_layout_toast, null, false);
        Text text = (Text) layout.findComponentById(ResourceTable.Id_msg_toast);
        text.setText(msg);
        new ToastDialog(getContext())
                .setContentCustomComponent(layout)
                .setSize(DirectionalLayout.LayoutConfig.MATCH_CONTENT, DirectionalLayout.LayoutConfig.MATCH_CONTENT)
                .setAlignment(LayoutAlignment.BOTTOM)
                .show();
    }
}
